//
//  ZQNewFeature.swift
//  新浪微博
//
//  Created by admin on 2020/7/20.
//  Copyright © 2020 huami. All rights reserved.
//

import UIKit

// 新特性
class ZQNewFeatureView: UIView {
 
    @IBOutlet weak var scrollView: UIScrollView!

    @IBOutlet weak var enterBtn: UIButton!
    @IBOutlet weak var pageControl: UIPageControl!

    class func newFeatureView() -> Self {
        let nib = UINib(nibName: "ZQNewFeatureView", bundle: nil )
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! Self
        return v
    }

    @IBAction func enterClick() {
        removeFromSuperview()
    }

    override func awakeFromNib() {
        let count = 4
        let rect = UIScreen.main.bounds
        for i in 0..<count {
            let imageName = "new_feature_\(i + 1)"
            let iv = UIImageView(image: UIImage(named: imageName))

            // 设置大小
            iv.frame = rect.offsetBy(dx: CGFloat(i) * rect.width, dy: 0)
            scrollView.addSubview(iv)
        }

        // 指定 scrollview 的属性
        scrollView.contentSize = CGSize(width: CGFloat(count + 1) * rect.width, height: rect.height)
        scrollView.bounces = false
        scrollView.isPagingEnabled = true
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.delegate = self

        enterBtn.isHidden = true
    }
}

extension ZQNewFeatureView: UIScrollViewDelegate {
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

        // 1. 滚动到最后一屏，让视图消失
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        print(page)

        // 2. 判断是否是最后一页
        if page == scrollView.subviews.count {
            print("欢迎")
            removeFromSuperview()
        }

        // 3. 如果是倒数第二页，显示按钮
        enterBtn.isHidden = (page != scrollView.subviews.count - 1)
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 计算当前用户的偏移量
        enterBtn.isHidden = true

        // 1. 计算当前的偏移量
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width + 0.5)

        // 2. 设置分页控件
        pageControl.currentPage = page

        // 3. 分页控件的隐藏
        pageControl.isHidden = (page == scrollView.subviews.count)
    }
}
